package com.hl.glidedemo.appWidget

import android.appwidget.AppWidgetManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.widget.ImageView
import android.widget.RemoteViews
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.hl.glidedemo.R

class MyWidgetIntentReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val appWidgetId = intent.getIntExtra(
            AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID
        )
        if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            val imageUrl = intent.getStringExtra("imageUrl")
            if (imageUrl != null) {
                loadImage(context, appWidgetId, imageUrl)
            }
        }
    }

    private fun loadImage(context: Context, appWidgetId: Int, imageUrl: String) {
        // 使用 Glide 加载图像
        Glide.with(context)
            .asBitmap()
            .load(imageUrl)
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadCleared(placeholder: Drawable?) {
                    // 清理资源
                }

                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    // 设置图像到 AppWidget
                    setImageViewBitmap(context, appWidgetId, R.id.imageView, resource)
                }
            })
    }

    private fun setImageViewBitmap(
        context: Context,
        appWidgetId: Int,
        imageViewId: Int,
        bitmap: Bitmap
    ) {
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val views = RemoteViews(context.packageName, R.layout.movie_widget_item)
        views.setImageViewBitmap(imageViewId,bitmap)
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
}